import {
	_decorator,
	Component,
	Input,
	input,
	Node,
	instantiate,
	Prefab,
	EventTouch,
	RigidBody,
	Vec3,
} from 'cc'
const { ccclass, property } = _decorator;

@ccclass('AttackBullet')
export class AttackBullet extends Component {
	@property
	public maxAttackNum: number = 1 // 最大攻击次数

	@property
	public testString: string = '' // 测试字符串

	@property(Prefab)
	public bulletPrefab: Prefab = null;

	@property
	public bulletSpeed: number = 40; // 子弹速度

	@property(Node)
	public bulletParent: Node = null;

	private isTouching:boolean = false;

	private bulletTimer: number = 0;


	private fireRate: number = 0.3;
    
 

	start() {
		input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
		input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
	}

	onTouchStart(event: EventTouch) {
	
		this.isTouching = true;

	}

	fire(){
		// 创建子弹
		const bullet = instantiate(this.bulletPrefab);
		bullet.setPosition(0, 0, 0);
		bullet.setWorldPosition(this.node.position) // 设置子弹位置为当前节点的世界位置
		// bullet.setPosition(this.node.position);
		// this.node.addChild(bullet);
		bullet.setParent(this.bulletParent)// 设置父节点为当前节点的父节点
		const rgb = bullet.getComponent(RigidBody)
		rgb.setLinearVelocity(new Vec3(0, 0,-this.bulletSpeed)); // 设置线性速度

	}




	 
	onTouchEnd(event: EventTouch) {
		this.isTouching = false;
		
		
	}

	update(deltaTime: number) {
		if (this.isTouching) {
			this.bulletTimer += deltaTime;
			if(this.bulletTimer > this.fireRate){
				this.fire()
				this.bulletTimer = 0;
			}

		}
	}
}


